<?php

namespace api\modules\mini\forms\user;

use common\models\patient\Patient;
use Yii;
use yii\base\Model;

/**
 * Class UserFeedbackForm
 * @package api\modules\mini\forms\user
 */
class UserFeedbackForm extends Model
{
    /**
     * @var int $patient_id 患者ID
     * @var string $content 意见内容
     */
    public $patient_id;
    public $content;

    /**
     * @var Patient $_patient
     */
    protected $_patient;


    public function rules()
    {
        return [
            // 参数验证
            [['patient_id', 'content'], 'required', 'message' => '{attribute}不能为空', 'on' => ['create']],

            [['patient_id'], 'checkPatientId', 'skipOnEmpty' => false, 'on' => ['create']],
            [['content'], 'checkContent', 'skipOnEmpty' => false, 'on' => ['create']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 新增
        $scenarios['create'] = ['patient_id', 'content'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'patient_id' => '客户',
            'content' => '意见',
        ];
    }

    /**
     * 检验姓名
     * @param $attribute
     * @return void
     */
    public function checkPatientId($attribute)
    {
        if ($this->hasErrors()) {
            return;
        }
        $patient = $this->getPatient();
        if (empty($patient)) {
            $this->addError($attribute, '客户不存在');
            return;
        }
        if ($patient->status == Patient::STATUS_DELETE) {
            $this->addError($attribute, '客户已删除');
            return;
        }
        if ($patient->user_id != Yii::$app->user->identity->member_id) {
            $this->addError($attribute, '客户非当前账号拥有');
            return;
        }
    }

    /**
     * 检验意见
     * @param $attribute
     * @return void
     */
    public function checkContent($attribute)
    {
        if ($this->hasErrors()) {
            return;
        }
        if (mb_strlen($this->content) > 512) {
            $this->addError($attribute, '意见超出长度[1-512位]');
            return;
        }
    }

    public function getPatient(): ?Patient
    {
        if (is_null($this->_patient)) {
            $this->_patient =  Patient::findOne($this->patient_id);
        }
        return $this->_patient;
    }
}